<template>

  <view class="index_container">
    <view class="top_container"> </view>
    <view class="scroll-y">
      <view class="info_box">
        <img
          :src="
            avartar
              ? 'http:' + avartar
              : 'https://img.xingkonglian.net/img/common/shop_default.png'
          "
          alt=""
          class="avatar"
        />
        <view class="user_name">{{ userinfo.mch_name }}</view>
        <view class="balance_container">
          <view class="frozen_balance flex-c">
            <view class="balance_text">冻结金额</view>
            <view class="balance_count">{{ userinfo.frozen_balance }}</view>
          </view>
          <view class="balance flex-c" @tap="go_balance">
            <view class="balance_text">余额</view>
            <view class="balance_count">{{ userinfo.balance }}</view>
            <text class="iconfont icon-dayuhao1"></text>
          </view>
        </view>
      </view>
      <view class="menu_container">
        <view class="menu_box1">
          <text class="menu_title">商品管理</text>
          <view class="box_container">
            <view
              class="menu_box"
              :id="`tip_2_${index}`"
              v-for="(item, index) in menuList"
              :key="index"
              @tap="go_menu(item)"
            >
              <image :src="item.pic" class="menupic"></image>
              <view class="menutitle">{{ item.title }}</view>
            </view>
          </view>
        </view>
        <view class="menu_box1">
          <text class="menu_title">订单查询</text>
          <view class="box_container" v-if="userinfo.org_type == 1">
            <view
              class="menu_box"
              v-for="(item, index) in menuList1_near"
              :key="index"
              @tap="go_menu(item)"
            >
              <image :src="item.pic" class="menupic"></image>
              <view class="menutitle">{{ item.title }}</view>
            </view>
          </view>
          <view class="box_container" v-else>
            <view
              class="menu_box"
              v-for="(item, index) in menuList1"
              :key="index"
              @tap="go_menu(item)"
            >
              <image :src="item.pic" class="menupic"></image>
              <view class="menutitle">{{ item.title }}</view>
            </view>
          </view>
        </view>
        <view class="menu_box1" v-if="userinfo.org_type == 1">
          <text class="menu_title">附近商家</text>
          <view class="box_container">
            <view
              class="menu_box"
              v-for="(item, index) in menuList2"
              :key="index"
              @tap="go_menu(item)"
            >
              <image :src="item.pic" class="menupic"></image>
              <view class="menutitle">{{ item.title }}</view>
            </view>
          </view>
        </view>
        <view class="menu_box1">
          <text class="menu_title">分析页</text>
          <view class="box_container">
            <view
              class="menu_box"
              :id="`tip_1_${index}`"
              v-for="(item, index) in menuList0"
              :key="index"
              @tap="go_menu(item)"
            >
              <image :src="item.pic" class="menupic"></image>
              <view class="menutitle">{{ item.title }}</view>
            </view>
          </view>
        </view>
        <view class="menu_box1">
          <text class="menu_title">工具</text>
          <view class="box_container">
            <view
              class="menu_box"
              v-for="(item, index) in menuList3"
              :key="index"
              @tap="go_menu(item)"
            >
              <image :src="item.pic" class="menupic"></image>
              <view class="menutitle">{{ item.title }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <van-popup
      :show="chongzhi_visible"
      @close="close_chongzhi"
      custom-style="popup"
    >
      <view class="kuaidi_container">
        <uinput
          placeholder="请输入充值金额"
          v-model="pay_param.price"
          label="充值金额"
          type="number"
        />
        <view class="btn_container">
          <van-button custom-class="btn" @tap="close_chongzhi">取消</van-button>
          <van-button custom-class="btn public" @tap="wxpay">支付</van-button>
        </view>
      </view>
    </van-popup>
    <van-dialog id="van-dialog" />
    <van-toast id="van-toast" />
  </view>
</template>

<script>
import Dialog from "../../wxcomponents/vant/dialog/dialog";
import {
  uc_info,
  withdraw,
  save_clients,
  wxpay,
  get_newest_app,
  orderpay_confirm,
} from "../../utils/imapi";
// import Toast from '../../wxcomponents/vant/toast/toast'
import { removeData } from "../../utils/storage";
import { intro } from "../../utils/intro";

const app = getApp();

export default {
  props: {},
  components: {},
  data() {
    return {
      userinfo: {},
      menuList0: [
        {
          pic: "/static/index/query_goods.png",
          title: "数据分析",
          url: "/pages/data_analyse/data_analyse",
        },
        {
          pic: "/static/index/bill_record.png",
          title: "账单记录",
          url: "/pages/record_list/record_list",
        },
        {
          pic: "/static/index/base_info.png",
          title: "基本信息",
          url: "/pages/mch_info/mch_info",
        },
      ],
      menuList: [
        {
          pic: "/static/index/query_goods.png",
          title: "商品查询",
          url: "/pages/query_goods/query_goods",
        },
        {
          pic: "/static/index/store_house.png",
          title: "仓库宝贝",
          url: "/pages/store_house/store_house",
        },
        {
          pic: "/static/index/liveplay_goods.png",
          title: "可直播宝贝",
          url: "/pages/live_goods/live_goods",
        },
        {
          pic: "/static/index/product_good1.png",
          title: "发布宝贝",
          url: "/pages/product_goods/product_goods",
        },
      ],
      menuList1: [
        {
          pic: "/static/index/orderlist.png",
          title: "全部订单",
          url: "/pages/order_list/order_list",
        },
        {
          pic: "/static/index/after_sale1.png",
          title: "待发货",
          url: "/pages/pre_express/pre_express",
        },
        {
          pic: "/static/index/complete.png",
          title: "交易完成",
          url: "/pages/complete_order/complete_order",
        },
        {
          pic: "/static/index/epxress.png",
          title: "售后",
          url: "/pages/after_sale/after_sale",
        },
      ],
      menuList1_near: [
        {
          pic: "/static/index/orderlist.png",
          title: "全部订单",
          url: "/pages/order_list/order_list",
        },
        {
          pic: "/static/index/after_sale.png",
          title: "待消费",
          url: "/pages/pre_express/pre_express",
        },
        {
          pic: "/static/index/complete.png",
          title: "交易完成",
          url: "/pages/complete_order/complete_order",
        },
        {
          pic: "/static/index/epxress.png",
          title: "售后",
          url: "/pages/after_sale/after_sale",
        },
      ],
      menuList2: [
        {
          pic: "/static/index/promotion.png",
          title: "推广产品",
          url: "/pages/promotion_goods/promotion_goods",
        },
        {
          pic: "/static/index/bargin_twitter.png",
          title: "砍价霸王餐",
          url: "/pages/near_mch_bargin/near_mch_bargin",
        },
        {
          pic: "/static/index/output.png",
          title: "曝光产品",
          url: "/pages/out_put/out_put",
        },

        {
          pic: "/static/index/scan.png",
          title: "扫一扫",
          url: "/pages/verification/verification",
        },
      ],
      menuList3: [
        {
          pic: "/static/index/bargin_twiter.png",
          title: "砍价推客版",
          url: "/pages/bargin_twitter/bargin_twitter",
        },
        // {
        //   pic: "/static/index/bargin_twiter.png",
        //   title: "附近商家砍价",
        //   url: "/pages/near_mch_bargin/near_mch_bargin",
        // },
        // {
        //   pic: "/static/index/bargin_twiter.png",
        //   title: "商家基本信息",
        //   url: "/pages/mch_info/mch_info",
        // },
        { pic: "/static/index/logout.png", title: "退出登录" },
      ],
      chongzhi_visible: false,
      money: "",
      providerList: [],
      pay_param: {
        price: "",
        in_out: "I",
        fin_type: "CZ",
        approve_status: "TJ",
        remark: "商家充值",
      },
      avartar:uni.getStorageSync('userinfo').mch_logo || ''
    };
  },
  computed:{
    newSteps(){ //写在computed这里，数据可以写成动
      var steps=[
        {
          element:'#tip_1_2',//目标元素
          //这里是每个引导框具体的文字内容，中间可以编写HTML代码
          intro: '<font style="color:#4f98fd;">第一步，填写完整商户信息，将商户帐户状态设为上线。</font>',
          //这里可以规定引导框相对于选中对象出现的位置 top,bottom,left,right
          position: 'top'//提示位置
        },
        {
          element:'#tip_2_3',//目标元素
          //这里是每个引导框具体的文字内容，中间可以编写HTML代码
          intro: '<font style="color:#4f98fd;">第二步，发布商品。 </font>',
          //这里可以规定引导框相对于选中对象出现的位置 top,bottom,left,right
          position: 'top'//提示位置
        },
        {
          element:'#tip_2_1',//目标元素
          //这里是每个引导框具体的文字内容，中间可以编写HTML代码
          intro: '<font style="color:#4f98fd;">第三步，将发布商品，从仓库中上架商品。 </font>',
          //这里可以规定引导框相对于选中对象出现的位置 top,bottom,left,right
          position: 'top'//提示位置
        },
      ]
      return steps

    }

  },
  watch: {},
  onLoad() {
    // this.get_newest_app('0.8');
    this.save_clients();
    // #ifdef APP-PLUS
    uni.getProvider({
      service: "payment",
      success: (e) => {
        console.log("payment success:" + JSON.stringify(e));
        let providerList = [];
        e.provider.map((value) => {
          switch (value) {
            case "wxpay":
              providerList.push({
                name: "微信",
                id: value,
                loading: false,
              });
              break;
            default:
              break;
          }
        });
        this.providerList = providerList;
      },
      fail: (e) => {
        console.log("获取支付通道失败：", e);
      },
    });
    // #endif
  },
  onReady() {

  },
  onShow() {
    const token = app.globalData.token || uni.getStorageSync("token");
    console.log(token);
    if (token) {
      this.uc_info();
    }
  },
  updated(){
    this.isOnceFn();
  },
  methods: {
    isOnceFn(){
      if(!uni.getStorageSync('isOnceInList')){//第一次进入则进行指引
        var Intro = intro()
        var steps=this.newSteps
        //配置
        Intro.setOptions({steps})
        this.$nextTick(()=>{//开始
          Intro.start()
        })
        //退出引导回调函数
        Intro.onexit(function(){
          uni.setStorageSync('isOnceInList',true);//isOnceInList==true即不是第一次进入啦
        })
      }
    },
    //访问引导页
    // 保存cid
    async save_clients() {
      if (app.globalData.cid) {
        try {
          const data = await save_clients({
            cid: app.globalData.cid,
            platform: "mch",
          });
          console.log();
        } catch (error) {}
      }
    },
    // 获取商家信息
    async uc_info() {
      try {
        const data = await uc_info();
        console.log(data);
        if (data.code == 0) {
          console.log(data.data.mch_logo);
          this.userinfo = data.data;
          app.globalData.userinfo = data.data;
          uni.setStorageSync("userinfo", data.data);
          console.log(app.globalData.userinfo);
        }
      } catch (error) {}
    },
    go_menu(item) {
      if (item.title == "退出登录") {
        Dialog.confirm({
          message: "确定要退出登录吗?",
        })
          .then(() => {
            // on confirm
            console.log("111");
            this.$toast.loading("退出登录中...");
            removeData("token");
            removeData("expre_time");
            app.globalData.token = "";
            setTimeout(() => {
              uni.navigateTo({
                url: "/pages/login/login",
              });
            }, 1000);
          })
          .catch(() => {
            // on cancel
          });
        return;
      }
      if (item.title == "商品查询" && this.userinfo.org_type == "1") {
        uni.navigateTo({
          url: item.url + "?type=near",
        });
        return;
      }
      uni.navigateTo({
        url: item.url,
      });
    },
    go_withdraw(money) {
      Dialog.confirm({
        title: "确定提现" + money + "元吗?",
      })
        .then(async () => {
          // on confirm
          const data = await withdraw({
            money,
          });
          if (data.code == 0) {
            this.$toast.success("提现申请成功");
          }
        })
        .catch(() => {
          // on cancel
        });
      // uni.navigateTo({
      //   url: "/pages/withdraw/withdraw",
      // });
    },

    // 打开充值
    open_chongzhi() {
      // if(this.providerList.length==0) {
      //   uni.showToast({
      //     title: '您未安装微信,无法支付',
      //     icon:'none'
      //   });
      //   return
      // }
      this.chongzhi_visible = true;
    },
    // 关闭充值
    close_chongzhi() {
      (this.pay_param.price = ""), (this.chongzhi_visible = false);
    },

    change_chongzhi_money(e) {
      console.log(e);
      this.money = e;
    },
    async wxpay() {
      const data = await this.getOrderInfo();
      // console.log(data);
      // const data = res.data
      // const bill_no = res.data.bill_no
      if (data.code == 0) {
        // const orderInfo = data.data;
        const orderInfo = data.data.payParam;
        const bill_no = data.data.bill_no;
        console.log(bill_no);
        console.log(orderInfo);
        uni.requestPayment({
          provider: "wxpay",
          orderInfo: orderInfo,
          success: async (e) => {
            console.log("success", e);
            const res = JSON.parse(e.rawdata);
            console.log(res._wxapi_payresp_prepayid);
            try {
              const res1 = await orderpay_confirm({
                trade_no: bill_no.toString(),
              });
              console.log(res1);
            } catch (error) {
              console.log(error);
            }
            uni.showToast({
              title: "充值成功!",
            });
            this.uc_info();
            this.close_chongzhi();
          },
          fail: (e) => {
            console.log("fail", e);
            uni.showModal({
              content: "支付失败,原因为: " + e.errMsg,
              showCancel: false,
            });
            this.close_chongzhi();
          },
          complete: (e) => {
            console.log(e);
            // this.providerList[index].loading = false;
          },
        });
      } else {
        uni.showToast({
          title: "操作失败,请稍后重试",
          icon: "none",
        });
      }
    },
    // 获取订单信息
    async getOrderInfo() {
      try {
        this.pay_param.price = Number(this.pay_param.price);
        console.log(this.pay_param);
        const data = await wxpay(this.pay_param);
        return data;
      } catch (error) {}
    },
    get_newest_app(ver) {
      plus.runtime.getProperty(plus.runtime.appid, async function (widgetInfo) {
        try {
          const result = await get_newest_app({
            version: ver,
          });
          var data = result.data;
          console.log(data);

          // 要更新 且有更新包地址
          if (data.update == 1 && data.upgradeUrl) {
            // 弹出 选择框 让用户选择是否更新，
            uni.showModal({
              title: "版本更新" + data.versionCode,
              content: data.description,
              confirmText: "更新",
              showCancel: true,
              success: function (e) {
                if (e.confirm) {
                  if (plus.os.name.toLowerCase() == "ios") {
                    // 跳转到下载页面
                    // plus.runtime.openURL(data.upgradeUrl)
                    uni.downloadFile({
                      url: data.upgradeUrl,
                      success: (downloadResult) => {
                        if (downloadResult.statusCode === 200) {
                          plus.runtime.install(
                            downloadResult.tempFilePath,
                            {
                              force: true,
                            },
                            function () {
                              console.log("install success...");
                              plus.runtime.restart();
                            },
                            function (e) {
                              console.error("install fail...");
                            }
                          );
                        }
                      },
                    });
                  } else {
                    var dtask = plus.downloader.createDownload(
                      data.upgradeUrl,
                      {},
                      function (d, status) {
                        uni.showToast({
                          title: "下载完成",
                          mask: false,
                          duration: 2000,
                        });
                        console.log(d.filename);
                        console.log(d.tempFilePath);
                        console.log(
                          plus.io.convertLocalFileSystemURL(d.filename)
                        );
                        // 下载完成  安装 force 一定要设置为true，更新完成后 重启应用
                        if (status == 200) {
                          plus.runtime.install(
                            plus.io.convertLocalFileSystemURL(d.filename),
                            {
                              force: true,
                            },
                            function () {
                              plus.runtime.restart();
                            },
                            function (error) {
                              uni.showToast({
                                title: "安装失败-01",
                                mask: false,
                                duration: 1500,
                              });
                            }
                          );
                        } else {
                          uni.showToast({
                            title: "更新失败-02",
                            mask: false,
                            duration: 1500,
                          });
                        }
                      }
                    );
                    try {
                      dtask.start(); // 开启下载的任务
                      var prg = 0;
                      var showLoading = plus.nativeUI.showWaiting("正在下载"); //创建一个showWaiting对象
                      dtask.addEventListener(
                        "statechanged",
                        function (task, status) {
                          // 给下载任务设置一个监听 并根据状态  做操作
                          switch (task.state) {
                            case 1:
                              showLoading.setTitle("正在下载");
                              break;
                            case 2:
                              showLoading.setTitle("已连接到服务器");
                              break;
                            case 3:
                              prg = parseInt(
                                (parseFloat(task.downloadedSize) /
                                  parseFloat(task.totalSize)) *
                                  100
                              );
                              showLoading.setTitle("  正在下载" + prg + "%  ");
                              break;
                            case 4:
                              plus.nativeUI.closeWaiting();
                              //下载完成
                              break;
                          }
                        }
                      );
                    } catch (err) {
                      plus.nativeUI.closeWaiting();
                      uni.showToast({
                        title: "更新失败-03",
                        mask: false,
                        duration: 1500,
                      });
                    }
                  }
                }
              },
            });
          }
        } catch (error) {}
      });
    },
    go_balance() {
      uni.navigateTo({
        url: "/pages/balance_page/balance_page",
      });
    },
  },
  onReachBottom() {},
  onHide() {},
};
</script>

<style scoped lang="scss" scoped>
.index_container {
  // position: relative;
  // display: flex;
  // flex-direction: column;
  // overflow: hidden;
  // height: 100vh;
  background: #f4f0fe;
}

.menu_box1 {
  background-color: #fff;
  border-bottom: 20rpx solid #f4f0fe;
  // margin-bottom: 20rpx;
  padding: 0 30rpx;
  .menu_title {
    // width: 100%;
    // padding-bottom: 10rpx;
    height: 70rpx;
    display: inline;
    line-height: 68rpx;
    font-size: 36rpx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #000000;
    border-bottom: 1px solid #eaedef;
  }
  .box_container {
    display: flex;
    flex-wrap: wrap;
  }
  .menu_box {
    width: 172.5rpx;
    height: 206rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .menupic {
      width: 104rpx;
      height: 104rpx;
      margin-bottom: 18rpx;
    }
    .menutitle {
      font-size: 28rpx;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #0a0819;
    }
  }
}
.scroll-y {
  // flex: 1;
  // position: relative;
  // overflow-y: scroll;
  position: relative;
  margin-top: 542rpx;
  overflow-y: auto;
  overflow: visible;
  z-index: 2;
}
.analyse {
  border-top: 1px solid #f0eefd;
}
/deep/ .custom-class {
  width: 80% !important;
  padding-bottom: 30rpx;
}
.btn_container {
  display: flex;
  justify-content: space-around;
  margin-top: 40rpx;
}
/deep/ .btn {
  min-width: 160upx;
  height: 64upx;
  background: #fff;
  border-radius: 10upx;
  font-size: 26upx;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #0a0819;
  line-height: 64upx;
  text-align: center;
  margin-left: 10upx;
}
/deep/ .public {
  background: #6d55ed !important;
  color: #ffffff !important;
}
.top_container {
  width: 100%;
  height: 424rpx;
  position: fixed;
  top: 0;
  left: -1rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  // background-color: pink;
  background-image: url("https://img.xingkonglian.net/img/common/top_bg.png");
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  z-index: 1;
}
.info_box {
  width: 668rpx;
  height: 318rpx;
  border-radius: 22rpx;
  position: absolute;
  top: -318rpx;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-image: url("https://img.xingkonglian.net/img/common/top_img.png");
  // background-image: url('https://img.xingkonglian.net/img/common/top_bg.png');
  background-position: 0 0;
  background-repeat: no-repeat;
  background-size: cover;
  z-index: 99;
}
.bg_pic {
  width: 750rpx;
  height: 300rpx;
  display: block;
}
.userinfo_container {
  width: 670rpx;
  height: 278rpx;
  background: #ffffff;
  border-radius: 12rpx;
  position: absolute;
  bottom: 24rpx;
  left: 50%;
  transform: translateX(-50%);
}
.mch_info {
  position: absolute;
  display: flex;
  flex-direction: column;
  align-items: center;
  top: -40rpx;
  left: 50%;
  transform: translateX(-50%);
}
.avatar {
  width: 228rpx;
  height: 228rpx;
  border-radius: 50%;
  position: absolute;
  top: -166rpx;
  left: 50%;
  transform: translateX(-50%);
}
.user_name {
  font-size: 48rpx;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #fff;
  margin-bottom: 34rpx;
  margin-top: 74rpx;
}
.balance_container {
  display: flex;
  justify-content: space-between;
  width: 320rpx;
  position: relative;
}
.balance {
  position: relative;
}
.icon-dayuhao1 {
  position: absolute;
  font-size: 40rpx;
  font-weight: 500;
  top: 50%;
  right: -60rpx;
  transform: translateY(-64%);
  color: #fff;
}
.balance_text {
  font-size: 32rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #fff;
  margin-bottom: 16rpx;
}
.balance_count {
  font-size: 36rpx;
  font-family: Helvetica;
  color: #fff;
}
/deep/ .mch_balance_container {
  padding: 0 40rpx;
  margin-top: 160rpx;
  .btn1 {
    width: 128rpx;
    height: 44rpx;
    text-align: center;
    border-radius: 22rpx;
    line-height: 44rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    margin-top: 4rpx;
  }
}
.balance_count {
  font-size: 36rpx;
  font-family: Helvetica;
  color: #fff;
}
/deep/ .with_btn {
  background: #f0eefd;
  color: #7962f4;
}
/deep/ .recharge_btn {
  background: #7962f4;
  color: #fff;
}
</style>
